<template>
  <div class="drawe-manage-container">
    <el-form ref="requestParams"
             :model="requestParams"
             label-width="70px">
      <el-col :span="6">
        <el-form-item label="项目名称">
          <el-select v-model="requestParams.project_id"
                     @change="changeProject"
                     class="common-style"
                     clearable>
            <el-option v-for="(item) in selectedProArr"
                       :key="item.project_id"
                       :label="item.project_name"
                       :value="item.project_id"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="图纸类型">
          <el-select v-model="requestParams.type"
                     class="common-style"
                     placeholder="请选择">
            <el-option v-for="item in draweTypeArr"
                       :key="item.value"
                       :label="item.name"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="版本号">
          <el-select v-model="requestParams.ver_no"
                     class="common-style"
                     placeholder="请选择">
            <el-option v-for="item in verArr"
                       :key="item.project_paper_version_id"
                       :label="item.name"
                       :value="item.project_paper_version_id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="创建时间">
          <el-date-picker v-model="timeArr"
                          type="daterange"
                          class="common-style"
                          @change="onTimeChange"
                          range-separator="-"
                          value-format="yyyy-MM-dd"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-button type="primary"
                   @click="onBatchAdd">批量新增</el-button>
        <el-button type="primary"
                   v-auth="'get-zheli-paper-button'"
                   @click="onGetDrawe">查看浙里建图纸</el-button>
      </el-col>
      <el-col :span="8"
              :offset="8"
              class="condition-right-button">
        <el-button type="primary"
                   @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-col>
      <el-col :span="24"
              class="table-box">
        <el-table :data="tableData"
                  :highlight-current-row="true"
                  border
                  :header-cell-style="{ background: '#f5f5f5' }">
          <el-table-column type="index"
                           label="序号"
                           sortable
                           width="100"
                           align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="project_name"
                           label="项目名称"
                           align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="major"
                           label="专业"
                           align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="设计图纸"
                           align="center"
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <span @click="downOrLookDrawe(scope.row)"
                    class="down-or-look">{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column label="图纸类型"
                           align="center"
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{scope.row.type==1?'深化设计图纸':'设计方设计图纸'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="project_paper_version"
                           label="版本号"
                           align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="WBS（项目设计与分解）"
                           align="center"
                           prop="resolve_wbs_name"
                           show-overflow-tooltip>
          </el-table-column>
          <!--<el-table-column label="状态"
                           align="center"
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="getIsConfirm(scope.row)==1?'conf':'none-conf'">{{getIsConfirm(scope.row)==1?'已确认':'未确认'}}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="created_at"
                           label="创建时间"
                           align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作"
                           align="center"
                           width="160px">
            <template slot-scope="scope">
              <el-button type="text"
                         @click="onDetail(scope.row)">详情</el-button>
              <el-button type="text"
                         @click="onEdit(scope.row)">编辑</el-button>
              <el-button type="text"
                         @click="onDel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="24">
        <el-pagination @current-change="handlePageChange"
                       @size-change="handleSizeChange"
                       :current-page="requestParams.page"
                       :page-size="requestParams.page_size"
                       layout="total,sizes,prev, pager, next, jumper"
                       :total="total"
                       align="center">
        </el-pagination>
      </el-col>
    </el-form>
    <!-- 查看PDF格式的文件 -->
    <el-dialog title="pdf格式的文件"
               :visible.sync="dialogVisible"
               width="60%"
               class="drawe-manage-pdf-style"
               :before-close="onBeforeClose">
      <DialogVisiblePdf :todosPdf="todosPdf"></DialogVisiblePdf>
    </el-dialog>
    <LookImgDialog v-if="lookImgDialog==true"
                   :lookImgDialog.sync="lookImgDialog"
                   :imgUrl.sync="imgUrl"></LookImgDialog>
  </div>
</template>

<script>
import DialogVisiblePdf from './components/DialogVisiblePdf';
import LookImgDialog from '../DeepDesignConfirm/component/LookImgDialog'
import { standardCodeApi } from '@/services/StandardCode';
import { draweManagementApi } from '@/services/ProjectCenter';
export default {
  components: {
    DialogVisiblePdf,//查看pdf文件
    LookImgDialog,//查看图片
  },
  data () {
    return {
      todosPdf: '',
      dialogVisible: false,//pdf格式的文件弹框
      lookImgDialog: false,
      imgUrl: '',//图片的链接
      objRow: {},
      tableData: [],
      timeArr: null,
      statusArr: [],
      total: 0,
      draweTypeArr: [],
      verArr: [],
      requestParams: {
        project_id: '',//项目id
        show_company_name: 1,
        show_project_name: 1,
        show_wbs_name: 1,
        version: '',//版本号
        type: '',
        page: 1,
        page_size: 10,
        create_start_time: '',
        create_end_time: '',
        is_page: 1,//1分页；0:不分页
      }
    }
  },
  methods: {
    changeProject (val) {//项目名称
      this.handlePageChange(1);//模糊查询
    },
    onBeforeClose (done) {
      this.todosPdf = '';//重置
      done()
    },
    downFile (url, fileName) {//下载文件
      this.$message.warning('正在下载!')
      // console.log('fileName=', fileName, fileName.replace(/\s*/g, ""))
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName.replace(/\s*/g, ""); // 自定义文件名
      link.click() // 下载文件
    },
    downOrLookDrawe (row) {//下载或查看当前文件
      let picUrl = row.pic_url;//当前点击的文件
      var index = picUrl.lastIndexOf('.') // 获取指定字符串最后一次出现的位置，返回index
      var str = picUrl.substr(index + 1) // substr(start, length) 抽取从start下标开始的length个字符，返回新的字符串
      let judgeIsImg = ['png', 'jpg', 'jpeg'].indexOf(str.toLowerCase()) !== -1;
      let judgeIsPdf = ['pdf'].indexOf(str.toLowerCase()) !== -1;//判断是否为pdf文件
      if (judgeIsImg == true && judgeIsPdf == false) {//图片
        this.imgUrl = picUrl;
        this.lookImgDialog = true;
      } else if (judgeIsPdf == true && judgeIsImg == false) {//非图片直接下载
        this.todosPdf = row.pic_url;
        this.dialogVisible = true;
      } else {//非图片类型且非pdf类型执行下载
        this.downFile(picUrl, row.name);
      }
    },
    getIsConfirm (row) {//是否确认
      let isConfirm = 0;
      if (row.status == 1) {
        isConfirm = 1
      };
      return isConfirm;
    },
    getPaperList () {//图纸列表
      draweManagementApi.getPaperList({
        params: this.requestParams
      }).then((res) => {
        this.tableData = res.data.list;
        this.total = res.data.total_count;
      }).catch((error) => {
        console.log(error)
      })
    },
    onBatchAdd () {//批量新增
      this.$router.push({ path: '/addOrEditDrawePaper' })
    },
    onGetDrawe () {//获取浙里建图纸
      draweManagementApi.getPaper({
        params: {
          project_id: this.requestParams.project_id
        }
      }).then((res) => {
        if (res.code == '0') {
          window.open(res.data, '_blank')
        }
      }).catch((error) => {
        console.log(error)
      })
      // this.$message.warning('开发中')
    },
    onSearch () {//查询
      this.handlePageChange(1);//查询
    },
    onReset () {//重置
      this.timeArr = null;//重置
      this.requestParams = this.$options.data().requestParams;//重置
      this.onSearch();//刷新
    },
    handleSizeChange (size) {//当前显示的最大条数
      this.requestParams.page_size = size;
      this.handlePageChange(1);
    },
    // 分页
    handlePageChange (page) {
      this.requestParams.page = page;
      this.getPaperList();//刷新
    },
    onTimeChange (timeV) {//日期改变时触发的事件
      this.requestParams.create_start_time = timeV == null ? '' : timeV[0] + '00:00:00';
      this.requestParams.create_end_time = timeV == null ? '' : timeV[1] + '23:59:59';
    },
    onDetail (row) {//深化图纸确认
      this.$router.push({ path: '/addOrEditDrawePaper', query: { type: 'detail', paper_id: row.paper_id } })
    },
    onEdit (row) {//编辑
      this.$router.push({ path: '/addOrEditDrawePaper', query: { type: 'edit', paper_id: row.paper_id } })
    },
    delPaper (row) {//删除图纸    
      draweManagementApi.delPaper({
        data: {
          paper_id: row.paper_id,//图纸主键值
        }
      }).then((res) => {
        if (res.code == 0) {
          this.handlePageChange(1);//刷新
          this.$message.success('删除成功')
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    onDel (row) {//删除
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        left: true
      }).then(() => {
        this.delPaper(row);//删除图纸
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取图纸类型标准码
    getdraweTypeArrCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'paperType',//图纸类型
        }
      }).then(res => {
        if (res.code === 0 && res.data.list) {
          this.draweTypeArr = res.data.list
          window.localStorage.setItem('platformPaperType', JSON.stringify(this.draweTypeArr))
        }
      }, err => {
        console.log(err)
      })
    },
  },
  watch: {
    '$store.state.choosedProject': {
      handler (newval) {
        this.project = newval
        this.requestParams.project_id = this.project.project_id;
        if (this.$store.state.choosedProjectList.length == 0) {
          this.selectedProArr = [newval];//默认首个
        }
        this.handlePageChange(1);//刷新
      },
      deep: true,
      immediate: true
    },
    //飞轮项目切换时更新列表数据
    '$store.state.choosedProjectList': {
      handler (newval) {
        if (newval.list.length > 0) {
          this.selectedProArr = newval.list
          this.requestParams.project_id = this.selectedProArr[0].project_id
        };
        if (newval.list.length == 0) {
          let local = window.localStorage.getItem('choosedProject') || '{}'
          this.selectedProArr = [JSON.parse(local)] || [];
          this.requestParams.project_id = this.selectedProArr[0].project_id || '';
        };
        this.handlePageChange(1);//模糊查询
      },
      deep: true
    },
  },
  async created () {
    let local = window.localStorage.getItem('choosedProject') || '{}';
    let chooseList = window.localStorage.getItem('choosedProjectList') || '[]';
    if (JSON.parse(chooseList).length > 0) {
      this.selectedProArr = JSON.parse(chooseList);
    } else {
      this.selectedProArr = [JSON.parse(local)];
    };
    let platformdraweTypeArr = window.localStorage.getItem('platformdraweTypeArr')
    if (platformdraweTypeArr) {
      this.draweTypeArr = JSON.parse(platformdraweTypeArr)
    } else {
      await this.getdraweTypeArrCode();//图纸类型
    };
    await this.onSearch();//查询
  },
  mounted () {

  }
}
</script>

<style lang="scss" scoped>
.drawe-manage-container {
  padding: 20px;
  .common-style {
    width: 100% !important;
  }
  .condition-right-button {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
  }
  .table-box {
    margin-top: 20px;
  }

  .none-conf {
    color: red;
  }
  .conf {
    color: green;
  }
}
</style>